package servlets;

import java.io.IOException;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.ArrayList;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import model.User;
import database.DBHandler;

/**
 * Servlet implementation class Users
 */
public class Users extends AServlet {
	private static final long serialVersionUID = 1L;

	protected void doGet(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		HttpSession session = request.getSession();
		if (session == null || session.getAttribute("LoginStatus") == null
				|| !(Boolean) session.getAttribute("LoginStatus")) {
			response.sendRedirect("index.jsp");
			return;
		}
		
		if (request.getParameter("deleteTarget") != null){
			try {
				doDeleteUser(request, response);
			} catch (Exception e) {
				e.printStackTrace();
				throw new ServletException();
			}
			return;
		}
		

		RequestDispatcher rd = getServletConfig().getServletContext()
				.getRequestDispatcher("//WEB-INF/JSP-Files/users.jsp");
		rd.forward(request, response);
		return;
	}

	private void doDeleteUser(HttpServletRequest request,
			HttpServletResponse response) throws ServletException{
			Connection con = DBHandler.getHandler().getLocalCon();
			String userName = request.getParameter("deleteTarget");
			User user;
			try {
				user = DBHandler.getHandler().getUser(userName,con);
			} catch (Exception e) {
				finishTransaction(con, false);
				e.printStackTrace();
				throw new ServletException();
			}
			ArrayList<String> courses = user.getCourses();
			
			for(String courseName:courses){
				try {
					doUnRegisterFromCourse(userName, courseName);
				} catch (Exception e) {
					finishTransaction(con, false);
					e.printStackTrace();
					throw new ServletException();
				}
			}
			
			try {
				DBHandler.getHandler().removeUser(userName, con);
			} catch (SQLException e) {
				finishTransaction(con, false);
				e.printStackTrace();
				throw new ServletException();
			}
			finishTransaction(con, true);
			DBHandler.getHandler().returnLocalCon(con);
			request.getSession().setAttribute("SuccessMessage", "User removed successfully");
			RequestDispatcher rd = getServletConfig().getServletContext()
			.getRequestDispatcher("/WEB-INF/JSP-Files/users.jsp");
			try {
				rd.forward(request, response);
			} catch (IOException e) {
			}
	}

	public boolean doUnRegisterFromCourse(String userName, String courseName) throws IOException, ClassNotFoundException, SQLException{
		Connection con = DBHandler.getHandler().getLocalCon();
		User user = DBHandler.getHandler().getUser(userName, con);
		if (!user.getCourses().contains(courseName)) {
			return false;
		}
		DBHandler.getHandler()
				.unRegisterUserFromCourse(userName, courseName, con);
		return true;
	}

	public void doPost(HttpServletRequest request, HttpServletResponse response)
	throws ServletException, IOException {
		String userName = (String) request.getSession().getAttribute("LoginName");
		String password = request.getParameter("password");
		String name = request.getParameter("name");
		String family = request.getParameter("family");
		String phone = request.getParameter("phone");
				
		if (!phone.equals("")){
			try{
				Long.parseLong(phone);
				if(phone.length()<7) throw new NumberFormatException();
			}
			catch(NumberFormatException e){
				forwardOnError(request, response, "DetailsUpdateError", "Error: Please input a legal phone number", "/WEB-INF/JSP-Files/home.jsp");
				return;
			}
		}

		DBHandler dbh = DBHandler.getHandler();
		Connection con = dbh.getLocalCon();
		try {
			dbh.updateUser(userName, password, name, family, phone, con);
		} catch (Exception e) {
			e.printStackTrace();
		}

		finishTransaction(con, true);
		DBHandler.getHandler().returnLocalCon(con);
		response.sendRedirect(request.getContextPath() + "/Home");
		return;
	}
}
